/*
 * @Author: wangjj3
 * @Date: 2022-12-26 15:01:00
 * @Description: uat环境切换身份和开发环境切换身份公共混入
 */
import { isEmpty, differenceBy } from 'lodash-es';
import { ProcessService, UserIdentityService } from 'jdf-jssdk';
import { bizServiceURL } from '@/api/utils/constants';

const switchIdentItiesMixin = {
  methods: {
    /**
     * 起草流程
     */
    async draft() {
      // 当为部门通知，部门业务函、部门业务通报流程时需要判断是否有权限起草
      const processService = new ProcessService(bizServiceURL);
      const [draftList, identityList] = await Promise.all([
        processService.getHaveDraftAuthIdentityList(this.processDefinitionKey, this.loginName),
        new UserIdentityService(bizServiceURL).getByLoginName(this.loginName)]);
      // 获取当前人身份列表
      // const identityList = await new UserIdentityService(bizServiceURL).getByLoginName(this.loginName);
      // 如果没有身份，则弹出提示
      if (isEmpty(identityList)) {
        this.$alert('未获取到起草人身份', '提示', {
          type: 'warning',
          callback: () => {
            this.closeWindow();
          }
        });
      }
      // 如果只有一个身份，则直接起草
      if (identityList.length === 1) {
        const [{ id }] = identityList;
        this.identityId = id;
        this.draftProcess();
      } else {
        // 找出不能起草的身份
        const notDraftList = differenceBy(identityList, draftList, 'id')?.map(t => ({
          ...t,
          disabled: true,
        }));
        // 如果有多个身份，则弹出选身份窗口
        this.identityList = [...draftList, ...notDraftList];
        // this.identityList = identityList;
        this.$refs.selectIdentity.show();
      }
    },
    /**
     * 点击流程模板进行起草
     * @param {Object} template 流程模板信息
     */
    async draftDraft(template) {
      this.template = template;
      // 当为部门通知，部门业务函、部门业务通报流程时需要判断是否有权限起草
      const processService = new ProcessService(bizServiceURL);
      const [draftList, identityList] = await Promise.all([
        processService.getHaveDraftAuthIdentityList(template.processDefinitionKey, this.loginName),
        new UserIdentityService(bizServiceURL).getByLoginName(this.loginName)]);
      // 获取当前人身份列表
      // const identityList = await new UserIdentityService(bizServiceURL).getByLoginName(this.loginName);
      if (identityList.length === 1) {
        const [{ id }] = identityList;
        this.selectIdentityId = id;
        this.draftProcess(
          template.processDefinitionKey,
          template.processDefinitionName,
          this.selectIdentityId,
          {},
          '/process-form'
        );
      } else {
        // 找出不能起草的身份
        const notDraftList = differenceBy(identityList, draftList, 'id')?.map(t => ({
          ...t,
          disabled: true,
        }));
        this.identityList = [...draftList, ...notDraftList];
        this.$refs.selectIdentity.show();
      }
    }
  }
};
export default switchIdentItiesMixin;
